import socket
import queue
import threading
import time

# 创建UDP socket
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 绑定本地地址和端口
local_addr = ('10.9.0.94', 6110)  # 参考网页。。。。。
udp_socket.bind(local_addr)
udp_socket.settimeout(5.0)  # 采集超时设置，默认5.0秒

# 创建一个全局变量作为缓存队列
data_queue = queue.Queue()

# 创建一个全局变量作为文件名，根据个人进行设置
file_name = "data_file.bin"

# 定义一个全局flag 用于退出数据采集线程
exit_flag = threading.Event()


# 程序启动提示代码打印
def log_print():
    for i in range(1,4,1):
        print(i)
    print('DEEP Data acquisition WORKING ......')


def receive_data():
    try:
        while not exit_flag.is_set():
            data = udp_socket.recv(1293)  # 参考网页。。。。。
            data_queue.put(data)
            print(f"Received data: {data}")
    except KeyboardInterrupt:
        print("KeyboardInterrupt received. Exiting thread.")
    except socket.timeout:
        print("No data received within the timeout period.")
    except socket.error as e:
        print(f"Socket error: {e}")


def write_to_file():
    with open(file_name, "ab") as file:
        while not exit_flag.is_set():
            data = data_queue.get()
            if data is None:
                break  # 数据为空，退出循环
            file.write(data)
            print(f"Stored to file: {data}")


if __name__ == "__main__":
    log_print()
    try:
        # 启动接收UDP数据的线程
        receive_thread = threading.Thread(target=receive_data)
        receive_thread.start()

        # 启动将数据写入文件的线程
        write_thread = threading.Thread(target=write_to_file)
        write_thread.start()

        # 主线程等待 KeyboardInterrupt
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("KeyboardInterrupt received. Notifying thread to exit.")
        # 设置退出标志，通知线程退出
        exit_flag.set()

        # 主线程等待receive_thread线程退出
        receive_thread.join()

        # 主线程等待write_thread线程退出
        write_thread.join()

        # 关闭UDP socket
        udp_socket.close()

        print("Main thread exiting.")
